/**
 * Main GUI , zusammenführung von allen GUIS und 
 * @author admin
 */
package temprom;

import DataBase.DBConnection;
import DataBase.DBQuery;
import javax.swing.JFrame;
import temprom.GUI.FrmStart;
import java.awt.event.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.Timer;
import temprom.GUI.FrmConfig;
import temprom.GUI.FrmData;
import temprom.GUI.LoginDialog;

/**
 *
 * @author admin
 */
public class MainGUI extends JFrame implements ActionListener {

    /**
     *
     */
    public boolean _isLoggedIn = false;
    private Timer timer;
    private int delay;
    private JTabbedPane pane;
    int drawCounter = 0;
    ArrayList<String> params;
    private ArrayList<Integer> arList = new ArrayList<Integer>();
    private int[] data2 = {
        0
    };
    // Thread starten für die Daten des USB-Gerätes
    private Thread tempRom;// (new TempROM(),"tempRomThread");

    /**
     * Creates new form MainGUI
     */
    public MainGUI() {
        initComponents();
        params = DBQuery.GetParameters(DBConnection.CreateConnection());
        this.setLocation(300, 500);
        FrmStart.b1.addActionListener(this);
        FrmConfig.b1.addActionListener(this);
        FrmData.b1.addActionListener(this);
        tabStart.SetParams(params);
        delay = 1000;
        timer = new Timer(delay, this);
        timer.start();
    }

    private void ArraListToIntArray() {
        data2 = new int[arList.size()];
        int i = 0;
        for (Integer integer : arList) {
            data2[i++] = integer;
        }

    }
    /**
     *
     * @return
     * übergiebt den Parameter
     */
    public String GetParam1()
    {
        return txtP1.getText();
    }

    /**
     * Event 1
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tabMain = new javax.swing.JTabbedPane();
        tabStart = new temprom.GUI.FrmStart();
        tabConfig = new temprom.GUI.FrmConfig();
        tabData = new temprom.GUI.FrmData();
        tabAdmin = new javax.swing.JPanel();
        lblP1 = new javax.swing.JLabel();
        lblP2 = new javax.swing.JLabel();
        lblP3 = new javax.swing.JLabel();
        txtP1 = new javax.swing.JTextField();
        txtP2 = new javax.swing.JTextField();
        txtP3 = new javax.swing.JTextField();
        btnSave = new javax.swing.JButton();
        lblUntereTemperatur = new javax.swing.JLabel();
        txtp1Temp = new javax.swing.JTextField();
        lblP2Temp = new javax.swing.JLabel();
        txtP2Temp = new javax.swing.JTextField();
        txtP3Temp = new javax.swing.JTextField();
        lblP3Temp = new javax.swing.JLabel();
        lblP4 = new javax.swing.JLabel();
        txtP4 = new javax.swing.JTextField();
        lblP4Temp = new javax.swing.JLabel();
        txtP4Temp = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("frmMain"); // NOI18N

        tabMain.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                tabMainStateChanged(evt);
            }
        });
        tabMain.addTab("Start", tabStart);
        tabMain.addTab("Konfiguration", tabConfig);
        tabMain.addTab("Daten", tabData);

        lblP1.setText("Parameter 1");

        lblP2.setText("Parameter 2");

        lblP3.setText("Parameter 3");

        btnSave.setText("Speichern");
        btnSave.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnSaveMouseClicked(evt);
            }
        });

        lblUntereTemperatur.setText("P1 Temperatur");

        txtp1Temp.setEnabled(false);

        lblP2Temp.setText("P2 Temperatur");

        txtP2Temp.setEnabled(false);

        txtP3Temp.setEnabled(false);

        lblP3Temp.setText("P3 Temperatur");

        lblP4.setText("Parameter 4");

        lblP4Temp.setText("P4 Temperatur");

        txtP4Temp.setEnabled(false);

        javax.swing.GroupLayout tabAdminLayout = new javax.swing.GroupLayout(tabAdmin);
        tabAdmin.setLayout(tabAdminLayout);
        tabAdminLayout.setHorizontalGroup(
            tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabAdminLayout.createSequentialGroup()
                .addGroup(tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(tabAdminLayout.createSequentialGroup()
                        .addGap(149, 149, 149)
                        .addComponent(txtP4, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(52, 52, 52)
                        .addComponent(lblP4Temp)
                        .addGap(53, 53, 53)
                        .addComponent(txtP4Temp, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, tabAdminLayout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addGroup(tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(tabAdminLayout.createSequentialGroup()
                                .addGroup(tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(lblP3)
                                    .addComponent(lblP2)
                                    .addComponent(lblP1)
                                    .addComponent(lblP4))
                                .addGap(53, 53, 53)
                                .addGroup(tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(txtP1)
                                    .addComponent(txtP2)
                                    .addComponent(txtP3, javax.swing.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE))
                                .addGap(52, 52, 52)
                                .addGroup(tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(lblP3Temp)
                                    .addComponent(lblP2Temp)
                                    .addComponent(lblUntereTemperatur))
                                .addGap(53, 53, 53)
                                .addGroup(tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(txtp1Temp)
                                    .addComponent(txtP2Temp)
                                    .addComponent(txtP3Temp, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                .addContainerGap(50, Short.MAX_VALUE))
        );
        tabAdminLayout.setVerticalGroup(
            tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabAdminLayout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(tabAdminLayout.createSequentialGroup()
                        .addGroup(tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblP1)
                            .addComponent(txtP1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblP2)
                            .addComponent(txtP2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblP3)
                            .addComponent(txtP3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(tabAdminLayout.createSequentialGroup()
                        .addGroup(tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblUntereTemperatur)
                            .addComponent(txtp1Temp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblP2Temp)
                            .addComponent(txtP2Temp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblP3Temp)
                            .addComponent(txtP3Temp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtP4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(lblP4))
                    .addGroup(tabAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lblP4Temp)
                        .addComponent(txtP4Temp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 111, Short.MAX_VALUE)
                .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(67, 67, 67))
        );

        tabMain.addTab("Admin", tabAdmin);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tabMain, javax.swing.GroupLayout.PREFERRED_SIZE, 569, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tabMain, javax.swing.GroupLayout.PREFERRED_SIZE, 397, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        getAccessibleContext().setAccessibleDescription("");
        getAccessibleContext().setAccessibleParent(tabMain);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tabMainStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_tabMainStateChanged
        pane = (JTabbedPane) evt.getSource();
        if (pane.getSelectedIndex() == 3) {
            if (!_isLoggedIn) {
                LoginDialog auth = new LoginDialog(this);
                auth.setVisible(true);

                if (!auth.isSucceeded()) {
                    pane.setSelectedIndex(0);
                } else {
                    _isLoggedIn = true;
                    ArrayList<String> params = DBQuery.GetParameters(DBConnection.CreateConnection());
                    if (params != null) {
                        txtP1.setText(params.get(0));
                        txtp1Temp.setText(params.get(1));
                        txtP2.setText(params.get(2));
                        txtP2Temp.setText(params.get(3));
                        txtP3.setText(params.get(4));
                        txtP3Temp.setText(params.get(5));
                        txtP4.setText(params.get(6));
                        txtP4Temp.setText(params.get(7));
                    }
                }
            }
        }
        // System.out.println("selectedIndex = " + selectedIndex);
        //if (!_isLoggedIn)
        // if(tabAdmin.)
    }//GEN-LAST:event_tabMainStateChanged

    private void btnSaveMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSaveMouseClicked
        boolean result = DBQuery.InsertUpdateParameter(DBConnection.CreateConnection(),
                txtP1.getText(),
                txtp1Temp.getText(),
                txtP2.getText(),
                txtP2Temp.getText(),
                txtP3.getText(),
                txtP3Temp.getText(),
                txtP4.getText(),
                txtP4Temp.getText());
        if (!result)
            JOptionPane.showMessageDialog(this,
                                "Erfolgreich gespeichert!",
                                "Speichern",
                                JOptionPane.INFORMATION_MESSAGE);
        else
        {
            JOptionPane.showMessageDialog(this,
                                "Fehler beim Speichern!",
                                "Speichern",
                                JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnSaveMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MainGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSave;
    private javax.swing.JLabel lblP1;
    private javax.swing.JLabel lblP2;
    private javax.swing.JLabel lblP2Temp;
    private javax.swing.JLabel lblP3;
    private javax.swing.JLabel lblP3Temp;
    private javax.swing.JLabel lblP4;
    private javax.swing.JLabel lblP4Temp;
    private javax.swing.JLabel lblUntereTemperatur;
    private javax.swing.JPanel tabAdmin;
    private temprom.GUI.FrmConfig tabConfig;
    private temprom.GUI.FrmData tabData;
    private javax.swing.JTabbedPane tabMain;
    private temprom.GUI.FrmStart tabStart;
    private javax.swing.JTextField txtP1;
    private javax.swing.JTextField txtP2;
    private javax.swing.JTextField txtP2Temp;
    private javax.swing.JTextField txtP3;
    private javax.swing.JTextField txtP3Temp;
    private javax.swing.JTextField txtP4;
    private javax.swing.JTextField txtP4Temp;
    private javax.swing.JTextField txtp1Temp;
    // End of variables declaration//GEN-END:variables

    @Override
    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == timer) {
            if (FrmStart.b1.isSelected() == true) {
                if (tempRom == null) {
                    tempRom = new Thread(new TempROM(tabStart.GetComPort()), "tempRomThread");
                    tempRom.start();
                }
                if (drawCounter % 2 == 0) {
                    try {
                        tabStart.SetData();
                    } catch (SQLException ex) {
                        Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    tabStart.validate();
                    arList.add(2 * drawCounter);

                } else {
                    try {
                        tabStart.SetData();
                    } catch (SQLException ex) {
                        Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    tabStart.validate();
                    arList.add(drawCounter);
                }

                ArraListToIntArray();
                drawCounter++;
            } else {
                if (tempRom != null) {
                    tempRom.interrupt();
                    tempRom = null;
                }
            }
        } else if (e.getActionCommand().equals("Weiter")) {
            if (pane != null) {
                pane.setSelectedIndex(2);
            }
        }
        else if (e.getActionCommand().equals("Export")) {
            String fileName = tabConfig.GetFileName();
            if (fileName.equals(""))
                fileName = "export.csv";
            
            String filePath = tabConfig.GetFilePath();            
            if (!filePath.endsWith("\\"))
            {
               filePath += "\\"; 
            }
            int result = DBQuery.GetDataFromRange(DBConnection.CreateConnection(),
                   tabData.GetDateFrom(), tabData.GetDateTill(), filePath + fileName);
            if (result != -1)
            JOptionPane.showMessageDialog(this,
                                "Export war erfolgreich!",
                                "Export",
                                JOptionPane.INFORMATION_MESSAGE);
        else
        {
            JOptionPane.showMessageDialog(this,
                                "Fehler beim Exportieren!",
                                "Export",
                                JOptionPane.ERROR_MESSAGE);
        }
        }
    }
}
